//
//  RoyaDialView.m
//  Test
//
//  Created by royasoft on 12-12-5.
//  Copyright (c) 2012年 royasoft. All rights reserved.
//

#import "RoyaDialView.h"
#import "RoyaDialViewDelegate.h"

#import "SDWebImage/SDImageCache.h"
#import "Reachability.h"

#import <UIKit/UIView.h>

#define CONFIGURE_BUTTON(BTN,X,Y,TITLE,TAG) {\
                                    self.BTN = [UIButton buttonWithType:UIButtonTypeCustom];\
                                    [self.BTN setFrame:CGRectMake(X, Y, widthOfButton, heightOfButton)];\
                                    [self.BTN setShowsTouchWhenHighlighted:YES];\
                                    [self.BTN setTintColor:[UIColor whiteColor]];\
                                    [self.BTN setBackgroundColor:[UIColor darkGrayColor]];\
                                    [self.BTN setTag:TAG];\
                                    [self.BTN addTarget:self action:@selector(onKeyPressed:) \
                                                forControlEvents:UIControlEventTouchUpInside];\
                                    [self addSubview:self.BTN];\
                                   }

#define PULL_DOWN_OFFSET 5.0



#define TAG_KEY_0    1111  // *
#define TAG_KEY_1    2222  // #
#define TAG_KEY_DIAL     3333 // 拨出
#define TAG_KEY_UNDO     4444 // 消除
#define TAG_KEY_OffOn    5555 //键盘收回

#define kDefaultTextFieldPhoneNumberHeight 30
#define kTextFieldPhoneNumberHeight 46
#define kKeyboardHeight 45
#define kDialKeyHeight 50


//private
@interface RoyaDialView(private)


-(void)setLayOn:(BOOL) isLayOn;

-(void)handleCall:(NSString *) phoneNum;

@end

@implementation RoyaDialView(private)

-(void)setLayOn:(BOOL)isLayOn
{
    CGFloat adjustOffset = (self.frame.size.height - self.txtNumber.frame.size.height)/2.0 + PULL_DOWN_OFFSET;
    if (isLayOn == YES) {
        adjustOffset *= -1;
    }
   
    CGPoint center = self.center;
    center.y += adjustOffset;
    self.center = center;
}


-(void)handleCall:(NSString *) phoneNum
{
    if(phoneNum.length){
        if ([self.delegate  respondsToSelector:@selector(onDialView:makePhoneCall:)]) {
            [self.delegate onDialView:self makePhoneCall:phoneNum];
        }else{
                NSString *num = [[NSString alloc] initWithFormat:@"telprompt://%@",phoneNum];
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:num]];
              }
    }
}

@end

//public
@implementation RoyaDialView

-(id)init
{
    CGRect frame = [[UIScreen mainScreen] applicationFrame];
//    frame.size.height = kTextFieldPhoneNumberHeight + kKeyboardHeight*4 + kDialKeyHeight;
    
    CGFloat dailHeight = kTextFieldPhoneNumberHeight + kKeyboardHeight*4 + kDialKeyHeight;
    frame.size.height = frame.size.height - 44 - 50;
    CGFloat adHeight = frame.size.height - dailHeight;
    
//    CGRect adRect = [];
    
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        CGFloat heightOfTextField = bIos6 ?  kTextFieldPhoneNumberHeight:kDefaultTextFieldPhoneNumberHeight;
        UIImageView *txtNumberBg = [[UIImageView alloc]initWithFrame:(CGRect){0, 0, frame.size.width,kTextFieldPhoneNumberHeight}];
        txtNumberBg.image = [UIImage imageNamed:@"Keyboard-input box.png"];
        [self addSubview:txtNumberBg];
        self.txtNumber = [[UITextField alloc]initWithFrame:CGRectMake(10, (kTextFieldPhoneNumberHeight-heightOfTextField)/2 + (bIos6?0:4), frame.size.width - 10,heightOfTextField)];
        [self.txtNumber setBorderStyle:UITextBorderStyleNone];
        [self.txtNumber setEnabled:NO];
        [self.txtNumber setPlaceholder:@"请输入手机号码"];
        self.txtNumber.text = @"";
        self.txtNumber.delegate = self;
        [self addSubview:self.txtNumber];
//        self.txtNumber.background = [UIImage imageNamed:@"Keyboard-input box.png"];
        
        CGFloat heightOfButton = kKeyboardHeight;
        CGFloat widthOfButton = frame.size.width / 3.0;
        
        //configure the number key
        CONFIGURE_BUTTON(btn1, 0, kTextFieldPhoneNumberHeight, @"1",1);
        [self.btn1 setBackgroundImage:[UIImage imageNamed:@"keyboard1.png"]
                             forState:UIControlStateNormal];
        [self.btn1 setBackgroundImage:[UIImage imageNamed:@"keyboard1-press.png"]
                             forState:UIControlStateHighlighted];

        CONFIGURE_BUTTON(btn2, widthOfButton , kTextFieldPhoneNumberHeight, @"2",2);
        [self.btn2 setBackgroundImage:[UIImage imageNamed:@"keyboard2.png"]
                             forState:UIControlStateNormal];
        [self.btn2 setBackgroundImage:[UIImage imageNamed:@"keyboard2-press.png"]
                             forState:UIControlStateHighlighted];
        
        CONFIGURE_BUTTON(btn3, widthOfButton*2, kTextFieldPhoneNumberHeight, @"3",3);
        [self.btn3 setBackgroundImage:[UIImage imageNamed:@"keyboard3.png"]
                             forState:UIControlStateNormal];
        [self.btn3 setBackgroundImage:[UIImage imageNamed:@"keyboard3-press.png"]
                             forState:UIControlStateHighlighted];
        
        CONFIGURE_BUTTON(btn4, 0, heightOfButton + kTextFieldPhoneNumberHeight, @"4",4);
        [self.btn4 setBackgroundImage:[UIImage imageNamed:@"keyboard4.png"]
                             forState:UIControlStateNormal];
        [self.btn4 setBackgroundImage:[UIImage imageNamed:@"keyboard4-press.png"]
                             forState:UIControlStateHighlighted];
        
        CONFIGURE_BUTTON(btn5, widthOfButton, heightOfButton + kTextFieldPhoneNumberHeight, @"5",5);
        [self.btn5 setBackgroundImage:[UIImage imageNamed:@"keyboard5.png"]
                             forState:UIControlStateNormal];
        [self.btn5 setBackgroundImage:[UIImage imageNamed:@"keyboard5-press.png"]
                             forState:UIControlStateHighlighted];
        
        
        CONFIGURE_BUTTON(btn6, widthOfButton*2, heightOfButton + kTextFieldPhoneNumberHeight, @"6",6);
        [self.btn6 setBackgroundImage:[UIImage imageNamed:@"keyboard6.png"]
                             forState:UIControlStateNormal];
        [self.btn6 setBackgroundImage:[UIImage imageNamed:@"keyboard6-press.png"]
                             forState:UIControlStateHighlighted];
        
        
        CONFIGURE_BUTTON(btn7, 0, heightOfButton*2 + kTextFieldPhoneNumberHeight, @"7",7);
        [self.btn7 setBackgroundImage:[UIImage imageNamed:@"keyboard7.png"]
                             forState:UIControlStateNormal];
        [self.btn7 setBackgroundImage:[UIImage imageNamed:@"keyboard7-press.png"]
                             forState:UIControlStateHighlighted];
        
        
        CONFIGURE_BUTTON(btn8, widthOfButton, heightOfButton*2 + kTextFieldPhoneNumberHeight, @"8",8);
        [self.btn8 setBackgroundImage:[UIImage imageNamed:@"keyboard8.png"]
                             forState:UIControlStateNormal];
        [self.btn8 setBackgroundImage:[UIImage imageNamed:@"keyboard8-press.png"]
                             forState:UIControlStateHighlighted];
        
        
        CONFIGURE_BUTTON(btn9, widthOfButton*2, heightOfButton*2 + kTextFieldPhoneNumberHeight, @"9",9);
        [self.btn9 setBackgroundImage:[UIImage imageNamed:@"keyboard9.png"]
                             forState:UIControlStateNormal];
        [self.btn9 setBackgroundImage:[UIImage imageNamed:@"keyboard9-press.png"]
                             forState:UIControlStateHighlighted];
        
        CONFIGURE_BUTTON(btn0, widthOfButton, heightOfButton*3 + kTextFieldPhoneNumberHeight, @"0",0);
        [self.btn0 setBackgroundImage:[UIImage imageNamed:@"keyboard0.png"]
                             forState:UIControlStateNormal];
        [self.btn0 setBackgroundImage:[UIImage imageNamed:@"keyboard0-press.png"]
                             forState:UIControlStateHighlighted];
        
        CONFIGURE_BUTTON(btnXin,0,heightOfButton*3 + kTextFieldPhoneNumberHeight, @"*",TAG_KEY_0);
        [self.btnXin setBackgroundImage:[UIImage imageNamed:@"keyboard+.png"]
                                forState:UIControlStateNormal];
        [self.btnXin setBackgroundImage:[UIImage imageNamed:@"keyboard+-press.png"]
                                forState:UIControlStateHighlighted];
        
        CONFIGURE_BUTTON(btnJing, widthOfButton*2, heightOfButton*3 + kTextFieldPhoneNumberHeight, @"#",TAG_KEY_1);
        [self.btnJing setBackgroundImage:[UIImage imageNamed:@"keyboard#.png"]
                                forState:UIControlStateNormal];
        [self.btnJing setBackgroundImage:[UIImage imageNamed:@"keyboard#-press.png"]
                                forState:UIControlStateHighlighted];
        
         //configure the funcion key
        CGFloat heightOfButton_old = heightOfButton;
        heightOfButton = kDialKeyHeight;
        
//        widthOfButton = 80;
//        CONFIGURE_BUTTON(btnOffOn,0,heightOfButton_old*4 + heightOfTextField, @"OffOn",TAG_KEY_OffOn);
//        [self.btnOffOn setBackgroundImage:[UIImage imageNamed:@"keyboad-fold.png"]
//                                forState:UIControlStateNormal];
        
        CGFloat widthOfButton_old = 0;
        widthOfButton = frame.size.width / 3.0 * 2;
        CONFIGURE_BUTTON(btnDial,widthOfButton_old,heightOfButton_old*4 + kTextFieldPhoneNumberHeight, @"Dial",TAG_KEY_DIAL);
        [self.btnDial setBackgroundImage:[UIImage imageNamed:@"keyboard-freecall.png"]
                             forState:UIControlStateNormal];
        [self.btnDial setBackgroundImage:[UIImage imageNamed:@"keyboard-freecall-press.png"]
                                forState:UIControlStateHighlighted];
        
        widthOfButton_old += widthOfButton;
        widthOfButton = frame.size.width / 3.0;
        CONFIGURE_BUTTON(btnUndo, widthOfButton_old, heightOfButton_old*4 + kTextFieldPhoneNumberHeight, @"Undo",TAG_KEY_UNDO);
        [self.btnUndo setBackgroundImage:[UIImage imageNamed:@"keyboard-Delete Entered.png"]
                             forState:UIControlStateNormal];
        [self.btnUndo setBackgroundImage:[UIImage imageNamed:@"keyboard-Delete Entered-press.png"]
                                forState:UIControlStateHighlighted];

        
        mIsLayOn = NO;
        [self setLayOn:mIsLayOn];
        self.backgroundColor = [UIColor darkGrayColor];
        
        for (UIView *view in self.subviews)
        {
            CGRect f = view.frame;
            f.origin.y += adHeight;
            view.frame = f;
        }
//        [self addADScroView];
    }
    return self;

}


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/
-(void)onKeyPressed:(id)sender
{
    UIButton *btn = (UIButton *)sender;
   NSInteger tag = [btn tag];
   NSString *text = self.txtNumber.text;
    switch (tag) {
       case TAG_KEY_0:
            [self playAudio:@"dtmf-1.caf"];
            self.txtNumber.text = [NSString stringWithFormat:@"%@*",text];
            break;
        case TAG_KEY_1:
            [self playAudio:@"dtmf-3.caf"];
            self.txtNumber.text = [NSString stringWithFormat:@"%@#",text];
            break;
       case TAG_KEY_DIAL:
            [self playAudio:@"cancel.caf"];
            [self handleCall:text];
            break;
       case TAG_KEY_UNDO:
            [self playAudio:@"back.aif"];
            if (text.length) {
                 self.txtNumber.text = [text stringByReplacingCharactersInRange:NSMakeRange(text.length-1, 1)
                                                                     withString:@""];
            }
            break;
        case TAG_KEY_OffOn:
            self.hidden = YES;
            break;
       default:
            [self playAudio:[NSString stringWithFormat:@"dtmf-%d.caf",tag]];
            self.txtNumber.text = [NSString stringWithFormat:@"%@%d",text,tag];
            break;
    }
    if ([self.delegate respondsToSelector:@selector(onDialView:dialNumber:withKey:)]) {
        [self.delegate onDialView:self dialNumber:text withKey:tag];
    }
    
}

-(void)showInView:(UIView *)view
{
    CGRect selfFrame = self.frame;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0)
    {
        selfFrame.origin.y = view.frame.size.height - selfFrame.size.height - 70;
    }else
    {
        selfFrame.origin.y = view.frame.size.height - selfFrame.size.height - 50;
    }
    self.frame = selfFrame;
    [view addSubview:self];
}

#pragma Delegate

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    mIsLayOn ? (mIsLayOn = NO) : (mIsLayOn = YES);
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    [self setLayOn:mIsLayOn];
    [UIView commitAnimations];
    self.txtNumber.text = @"";
}

#pragma mark - audio methods
- (void)playAudio:(NSString *)fileName
{
    NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
    BOOL bPlay = [standard boolForKey:kDefaultVoiceSwitch]; // 拨号声音开关
    if (!bPlay)
    {
        return;
    }
    
    NSError *error;
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:fileName
                                                              ofType: nil];
    
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
    
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    
    appSoundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
//    [fileURL release];
    
    appSoundPlayer.numberOfLoops = 1;
    // AudioSessionSetActive(true);
    
    [appSoundPlayer prepareToPlay];
    //[_appSoundPlayer setVolume: 0.0];
    [appSoundPlayer setDelegate: (id)self];
    [appSoundPlayer play];
}

#pragma mark - audio
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [player stop];
    appSoundPlayer = nil;
//    [player release];
}

#pragma mark - SGFocusImageFrameDelegate and method
#define kDefaultCountOfPage 1

-(void)removeAd
{
    if (_midImageFrame)
    {
        _midImageFrame.delegate = nil;
        [_midImageFrame removeFromSuperview];
        _midImageFrame = nil;
    }
}

-(void)addADScroView
{
    
    CGRect frame = [[UIScreen mainScreen] applicationFrame];
    //    frame.size.height = kTextFieldPhoneNumberHeight + kKeyboardHeight*4 + kDialKeyHeight;
    CGFloat dailHeight = kTextFieldPhoneNumberHeight + kKeyboardHeight*4 + kDialKeyHeight;
    frame.size.height = frame.size.height - 44 - 50;
    CGFloat adHeight = frame.size.height - dailHeight;
    CGRect adFrame = (CGRect){0, 0, frame.size.width,adHeight};
    
    NSMutableArray *itemArray = nil;
    NSMutableArray *adUrls = nil;
    NSUserDefaults *usr = [NSUserDefaults standardUserDefaults];
    NSArray *arraryUrls = [usr objectForKey:kDefaultHalfAdInfo];
    if ([arraryUrls count] > 1)
    {
        adUrls = [[NSMutableArray alloc]initWithCapacity:3];
        NSInteger count = [arraryUrls count];
        srand((unsigned)time(0));
        NSInteger rand1 = rand()% count;
        [adUrls addObject:[arraryUrls objectAtIndex:rand1]];
    }
    else
    {
        adUrls = [[NSMutableArray alloc]initWithArray:arraryUrls];
    }
    
    NSMutableArray *imageNames = [[NSMutableArray alloc]initWithCapacity:3];
    [imageNames addObject:@"half.png"];
    
    NSInteger tag = 0;
    if([adUrls count] > 0)
    {
        int length = [adUrls count];
        //添加最后一张图 用于循环
        itemArray = [NSMutableArray arrayWithCapacity:length + 2*kDefaultCountOfPage];
        if (length > kDefaultCountOfPage)
        {
            for (int i = 0; i < kDefaultCountOfPage; i++, tag++)
            {
                NSString *url = [adUrls objectAtIndex:length-1-i];
                if (bIos6)
                {
                    SDImageCache *cache = [SDImageCache sharedImageCache];
                    if (![cache diskImageExistsWithKey:url]) {
                        url = imageNames[i % 3];
                    }
                }
                
                NSString *title = [NSString stringWithFormat:@"title%d",tag+1];
                SGFocusImageItem *item = [[SGFocusImageItem alloc] initWithTitle:title image:url tag:tag];
                [itemArray addObject:item];
            }
        }
        
        for (int i = 0; i < adUrls.count; i++, tag++)
        {
            NSString *url = adUrls[i];
            
            if (bIos6)
            {
                SDImageCache *cache = [SDImageCache sharedImageCache];
                if (![cache diskImageExistsWithKey:url]) {
                    url = imageNames[i % 3];
                }
            }
            
            NSString *title = [NSString stringWithFormat:@"title%d",tag+1];
            SGFocusImageItem *item = [[SGFocusImageItem alloc] initWithTitle:title image:url tag:tag];
            [itemArray addObject:item];
        }
        
        //添加第一张图 用于循环
        if ([adUrls count] > kDefaultCountOfPage)
        {
            for (int i = 0; i < kDefaultCountOfPage; i++, tag++)
            {
                NSString *url = adUrls[i];
                
                if (bIos6)
                {
                    SDImageCache *cache = [SDImageCache sharedImageCache];
                    if (![cache diskImageExistsWithKey:url]) {
                        url = imageNames[i % 3];
                    }
                }
                
                NSString *title = [NSString stringWithFormat:@"title%d",tag+1];
                SGFocusImageItem *item = [[SGFocusImageItem alloc] initWithTitle:title image:url tag:tag];
                [itemArray addObject:item];
            }
        }
    }
    else
    {
        int length = [imageNames count];
        //添加最后一张图 用于循环
        itemArray = [NSMutableArray arrayWithCapacity:length + 2*kDefaultCountOfPage];
        if (length > kDefaultCountOfPage)
        {
            for (int i = 0; i < kDefaultCountOfPage; i++, tag++)
            {
                NSString *url = [imageNames objectAtIndex:length-1-i];
                NSString *title = [NSString stringWithFormat:@"title%d",i+1];
                SGFocusImageItem *item = [[SGFocusImageItem alloc] initWithTitle:title image:url tag:tag];
                [itemArray addObject:item];
            }
        }
        
        for (int i = 0; i < [imageNames count]; i++, tag++)
        {
            NSString *url = imageNames[i];
            NSString *title = [NSString stringWithFormat:@"title%d",i+1];
            SGFocusImageItem *item = [[SGFocusImageItem alloc] initWithTitle:title image:url tag:tag];
            [itemArray addObject:item];
        }
        
        //添加第一张图 用于循环
        if ([imageNames count] > kDefaultCountOfPage)
        {
            for (int i = 0; i < kDefaultCountOfPage; i++, tag++)
            {
                NSString *url = imageNames[i];
                NSString *title = [NSString stringWithFormat:@"title%d",i+1];
                SGFocusImageItem *item = [[SGFocusImageItem alloc] initWithTitle:title image:url tag:tag];
                [itemArray addObject:item];
            }
        }
    }
    
    if (itemArray.count > 0) {
        _midImageFrame =  [[SGFocusImageFrame alloc] initWithFrame:adFrame delegate:(id)self imageItems:itemArray isAuto:YES];
        [self addSubview:_midImageFrame];
    }
}

//获取图片的边距
- (CGFloat)getOffsetDisFromSide
{
    return 0;
}
// 一页有几个item
- (int)getCountOfOnePage
{
    return kDefaultCountOfPage;
}
@end